"""
Copyright (c) 2023 - present SKbioinfo
"""
from flask_restful import Resource
from flask import request,jsonify,current_app
from apps.config import ProductionConfig
from apps.API.utils.log_helper import lg
from apps.API.connector.db_common import *
from apps.API.common.common_time import *
from apps.API.common.db_table_config import *
from flask_jwt_extended import jwt_required
import yaml,os

class interfaceBasicSetting(Resource):
    def _read_config(self,config_dir):
        config={}
        with open(f"{config_dir}/config.yaml",'r') as f:
            config=yaml.safe_load(f)
        return config
    
    @jwt_required()
    def get(self):
        try:
            config_dir="/".join(os.path.dirname(os.path.abspath(__file__)).split("/")[:-2])
            config=self._read_config(config_dir)
            response=jsonify(config)
            response.status=202
            return response
        except Exception as e:
            lg.error(e)
            return 404

    @jwt_required()
    def post(self):
        try:
            config_dir="/".join(os.path.dirname(os.path.abspath(__file__)).split("/")[:-2])
            config=self._read_config(config_dir)
            updateConfig={}
            for key,value in request.json.items():
                config[key]=value
                for key,value in value.items():
                    updateConfig[key]=value
            with open(f'{config_dir}/config.yaml',"w") as f:
                yaml.dump(config,f,default_flow_style=False)
            current_app.config.update(updateConfig)
            response=jsonify({})
            response.status=202
            return response
        except Exception as e:
            lg.error(e)
            return 404
        
